package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.TransactionAnnotationParser;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date:2022-11-04
 * Time:22:26
 *
 * @Author: 东莞呵呵
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @RequestMapping("add")
    public int addUser(UserInfo userInfo) throws InterruptedException {
        //非空校验
        if(userInfo==null|| !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())){
            return -1;
        }
        //开启事务
        TransactionStatus status=
                dataSourceTransactionManager.getTransaction(transactionDefinition);
        int result = userService.addUser(userInfo);
        System.out.println(result);
        //回滚事务
        dataSourceTransactionManager.rollback(status);
        //提交事务
        dataSourceTransactionManager.commit(status);
        return result;
    }

    @Transactional
    @RequestMapping("/add2")
    public int add2(UserInfo userInfo) throws InterruptedException {

        userService.addUser(userInfo);
        try {
            throw new RuntimeException();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return 1;
    }
}
